<?php

namespace App\Services;

use App\Models\HardwareList;
use Slowlyo\OwlAdmin\Services\AdminService;

/**
 * 硬件管理
 *
 * @method HardwareList getModel()
 * @method HardwareList|\Illuminate\Database\Query\Builder query()
 */
class HardwareListService extends AdminService
{
	protected string $modelName = HardwareList::class;

	// 更新记录时 将变动参数 整理下来 添加到动线记录中
	public function update($primaryKey, $data): bool
	{
		// 获取更新前的数据
		$model = $this->query()->whereKey($primaryKey)->first();
		
		$result = parent::update($primaryKey, $data);
		
		if ($result) {
			// 检查所有需要追踪的字段变动
			$changes = [];
			$fieldsToTrack = [
				'category' => '硬件分类',
				'brand_name' => '品牌型号', 
				'sn_code' => '硬件SN码',
				'configuration' => '硬件配置',
				'purchase_date' => '购买日期',
				'current_location' => '当前位置',
				'user_department' => '使用方',
				'statuss' => '状态'
			];

			foreach ($fieldsToTrack as $field => $fieldName) {
				if (isset($data[$field]) && $model->$field != $data[$field]) {
					$changes[] = "{$fieldName}: {$model->$field} → {$data[$field]}";
				}
			}

			// 如果有字段发生变更，记录到变更记录表
			if (!empty($changes)) {
				app(\App\Services\HardwareMoveRecordService::class)->store([
					'hardware_id' => $primaryKey,
					'sn_code' => $model->sn_code,
					'previous_location' => $model->current_location,
					'after_location' => $data['current_location'] ?? $model->current_location,
					'move_time' => now()->format('Y-m-d H:i:s'),
					'move_remark' => implode('; ', $changes),
				]);
			}
		}
		
		return $result;
	}
}
